import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// Layout
import Layout from '@/layout'

// 路由表
const routes = [
  /**
   * meta属性
   *  cache   Boolean   页面是否被 <keep-alive> 缓存（解决详情页返回列表页）
   *  title   String    页面标题
   */

  // tabbar 页面
  {
    path: '/',
    component: Layout,
    name: 'Layout',
    redirect: '/home',
    meta: { cache: true },
    children: [
      {
        path: 'home',
        name: 'HomePage',
        component: () => import('@/views/tabbar-page/home')
      },
      {
        path: 'cinema',
        name: 'cinemaPage',
        component: () => import('@/views/tabbar-page/cinema')
      },
      {
        path: 'profile',
        name: 'ProfilePage',
        component: () => import('@/views/tabbar-page/profile')
      }
    ]
  },

  {
    path: '/city-select',
    name: 'CitySelect',
    meta: { title: '选择城市' },
    component: () => import('@/views/child-page/city-select')
  },

  {
    path: '/search',
    name: 'Search',
    meta: { title: '搜索', cache: true },
    component: () => import('@/views/child-page/search')
  },

  {
    path: '/film-detail/:filmId(\\d+)',
    name: 'FilmDetail',
    meta: { title: '影片详情', cache: true },
    props: true,
    component: () => import('@/views/child-page/film-detail')
  },

  {
    path: '/cinema-detail/:cinemaId(\\d+)',
    name: 'CinemaDetail',
    meta: { title: '影院详情', cache: true },
    props: true,
    component: () => import('@/views/child-page/cinema-detail')
  },

  {
    path: '/403',
    name: 'Page403',
    meta: { title: '403' },
    component: () => import('@/views/error-page/403')
  },
  {
    path: '/404',
    name: 'Page404',
    meta: { title: '404' },
    component: () => import('@/views/error-page/404')
  },
  {
    path: '*', 
    redirect: '/404'
  }
]

// 路由工厂
const createRouter = () => new VueRouter({
  routes
})

// 生成路由
const router = createRouter()

// 路由重置
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

// 解决 a 页跳转 b 页时通过路由守卫 next 到其他页面时的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router